#!/usr/bin/python
import SocketServer,sys,re,time,thread,threading,os,socket,random
import  struct, fcntl
class Interface_ip:
	def set_interface(self,ifname):
		self.ifname = ifname
	def get_ip_address(self):
	    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	    return socket.inet_ntoa(fcntl.ioctl(
	        s.fileno(),
	        0x8915,  # SIOCGIFADDR
	        struct.pack('256s', self.ifname[:15])
	    )[20:24])
Mcache = []
class BootStrapHandler(SocketServer.BaseRequestHandler):
	def PadMsg(msg):
        	while len(msg) < 1024:
                	msg=msg+' '
        	return msg

	def server_bind(self):
		SocketServer.ThreadingTCPServer.server_bind(self)
		self.socket.setdefaulttimeout(5)
		self.run = True

	def setup(self):
		print 'BootStrap: ',self.client_address, ' conectou' 
		
	def handle(self):
		try:
			global Mcache
			global McacheNode
			#Get command
			
			Saida=False
			while Saida!=True:
				data = self.request.recv(1024)
				if data.strip() != '':
					print 'BootStrap Recebeu: ',data.strip()
				else:
					pass
				if data.strip() == 'REGISTER':
					#Coloco o peer na lista de peers
					if Mcache.count(self.client_address[0]) <= 0:
						Mcache.append(str(self.client_address[0]))
                                                self.request.send('OK\r\n')
					else:
						pass

				elif data.strip() == 'REMOVE':
					data = self.request.recv(1024)
					while data.strip() != 'FINISH':
						print data.strip()
						if Mcache.count(data.strip()) > 0:
							Mcache.remove(data.strip())
						else:
							print 'ERRO' 
						data = self.request.recv(1024)

				elif data.strip() == 'LIST':
					Mcache = ['127.0.0.1','192.168.1.3','192.168.1.3','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7']
					#Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3','192.168.1.12','192.168.1.15']
					#Mcache = ['127.0.0.1','192.168.1.1','192.168.1.2','192.168.1.3']
					McacheNode = Mcache[:]
					McacheNode.remove(self.client_address[0])
					if Mcache.count(self.client_address[0]) >0:
						if len(McacheNode) <= 5 and len(McacheNode) > 0:
							for Ip in McacheNode:
								self.request.send(str(Ip)+'\r\n')	
						elif len(McacheNode) > 5:
							peerSelect = []
							while len(peerSelect) < 5:
								peerIp = random.choice(McacheNode)
								print peerIp
								if peerSelect.count(peerIp) == 0:
									peerSelect.append(peerIp)
							for Ip in peerSelect:
								self.request.send(str(Ip)+'\r\n')
						else:
							IpServer = Interface_ip()
							IpServer.set_interface('eth0')
							Ip = IpServer.get_ip_address()
							self.request.send(str(Ip)+'\r\n')
					else:
						pass	
				elif data.strip() == 'EXIT':
					Saida=True
				elif data.strip() == '':
					pass	
					
				else:
					pass
		except :
			self.finish()
	def finish(self):
		print 'BootStrap: ',self.client_address,' desconectou'
		print repr(McacheNode)
		print repr(Mcache)

def open_bootstrap():
	SocketServer.ThreadingTCPServer.allow_reuse_address = 1
	BootStrapPort = 7187
	print 'BootStrap inicializado na porta: ' + str(BootStrapPort) 
	bootstrap = SocketServer.ThreadingTCPServer(('',BootStrapPort), BootStrapHandler)
	try:
		bootstrap.serve_forever()
	except KeyboardInterrupt:
		sys.exit(0)

def Initialize():
	thread.start_new_thread(open_bootstrap,())
	time.sleep(1)
Initialize()
while 1:pass
